package cn.hh.redis.controller;

import cn.hh.redis.annotation.CheckSmsCode;
import cn.hh.redis.util.RedisCache;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangh
 * @date 2021/11/30
 * @Description:
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private RedisCache redisCache;

    @RequestMapping("/sendSms")
    //@CheckSmsCode
    public String sendSms(@RequestBody(required=false) Map<String,Object> param,
                        @RequestParam(required=false)  Map<String,Object> param1,
                        @RequestHeader Map<String,Object> headParam){
        System.out.println("sms sendSms.....");
        String result = RandomUtil.randomNumbers(4);
        redisCache.setCacheObject("smsCode",result,5, TimeUnit.MINUTES);
        return result;
    }


    @RequestMapping("/checkSmsCode")
    public String checkSmsCode(@RequestBody(required=false) Map<String,Object> param,
                          @RequestParam(required=false)  Map<String,Object> param1,
                          @RequestHeader Map<String,Object> headParam){
        System.out.println("sms checkSmsCode.....");
        String result = "";
        String smsCode = StrUtil.toString(param1.get("code"));
        String redisCode = redisCache.getCacheObject("smsCode");

        if(smsCode.equals(redisCode)){
            result = "短信验证成功";
            redisCache.setCacheObject("smsCheck","true",5,TimeUnit.MINUTES);
            redisCache.deleteObject("smsCode");
        }else{
            result = "短信验证失败";
        }

        return result;
    }
}
